@file:Suppress("UNCHECKED_CAST")

package com.roger.ndtplayer.commom.core

import android.os.Parcelable
import com.tencent.mmkv.MMKV


/**
 * MMKVHelper
 */
object MMKVHelper {

    var myMMKV: MMKV

    init {
        myMMKV = MMKV.defaultMMKV()
    }


    @JvmOverloads
    fun <T> getMMKVValue(
        key: String,
        defaultVal: T
    ): T {
        return when (defaultVal) {
            is Boolean -> myMMKV.decodeBool(key, defaultVal) as T
            is String -> myMMKV.decodeString(key, defaultVal) as T
            is Int -> myMMKV.decodeInt(key, defaultVal) as T
            is Long -> myMMKV.decodeLong(key, defaultVal) as T
            is Float -> myMMKV.decodeFloat(key, defaultVal) as T
            is Parcelable -> myMMKV.decodeParcelable(key, defaultVal.javaClass) as T
            is Set<*> -> myMMKV.getStringSet(key, defaultVal as Set<String>) as T
            else -> throw IllegalArgumentException("Unrecognized default value $defaultVal")
        }
    }

    @JvmOverloads
    fun <T> putMMKVValue(
        key: String,
        value: T
    ) {
        when (value) {
            is Boolean -> myMMKV.encode(key, value)
            is String -> myMMKV.encode(key, value)
            is Int -> myMMKV.encode(key, value)
            is Long -> myMMKV.encode(key, value)
            is Float -> myMMKV.encode(key, value)
            is Parcelable -> myMMKV.encode(key, value)
            is Set<*> -> myMMKV.encode(key, value as Set<String>)
            else -> throw UnsupportedOperationException("Unrecognized value $value")
        }
    }

    @JvmOverloads
    fun removeMMKVValue(key: String) {
        myMMKV.removeValueForKey(key)
    }

    @JvmOverloads
    fun clearAllMMKVValue() {
        myMMKV.clearAll()
    }
}